package org.example.y24.m11;

public class GaussSeidel {
    //系数矩阵A
    private double[][] A;
    //常数项向量B
    private double[] B;
    //线性方程组方程个数
    private int n;
    double epsilon = 1e-4;
    double[] x;
    int maxIterations = 1000000;
    //构造函数
    public GaussSeidel(){
        n = 4;
        A = new double[][]{
                {10, -1, 2, 0},
                {-1, 11, -1, 3},
                {2, -1, 10, -1},
                {0, 3, -1, 8}};
        B = new double[]{6, 25, -11, 15};
        x = new double[n];
    }
    //求解近似解
    public void solve(){
        int n = A.length;
        double[] xNew = new double[n];
        int iteration = 0;
        boolean converged = false;

        while (iteration < maxIterations && !converged) {
            for (int i = 0; i < n; i++) {
                double sum1 = 0.0;
                double sum2 = 0.0;
                for (int j = 0; j < i; j++) {
                    sum1 += A[i][j] * xNew[j]; // 已经更新过的x值
                }
                for (int j = i + 1; j < n; j++) {
                    sum2 += A[i][j] * x[j]; // 未更新的x值
                }
                xNew[i] = (B[i] - sum1 - sum2) / A[i][i];
            }

            // 检查是否收敛
            converged = true;
            for (int i = 0; i < n; i++) {
                if (Math.abs(xNew[i] - x[i]) > epsilon) {
                    converged = false;
                    break;
                }
            }

            // 更新解向量
            for (int i = 0; i < n; i++) {
                x[i] = xNew[i];
            }

            iteration++;
        }

        // 输出结果
        if (converged) {
            System.out.println(iteration + "次迭代找到的解决方案:");
            for (int i = 0; i < n; i++) {
                System.out.println("x[" + i + "] = " + x[i]);
            }
        } else {
            System.out.println("在最大迭代次数内解决方案不收敛。");
        }
    }

    public static void main(String[] args) {
        new GaussSeidel().solve();
    }
}
